<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="收料通知单号" prop="receiveId">
        <el-input
          v-model="queryParams.receiveId"
          placeholder="请输入收料通知单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采购订单号" prop="poId">
        <el-input
          v-model="queryParams.poId"
          placeholder="请输入采购订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="送货单号" prop="deliveryId">
        <el-input
          v-model="queryParams.deliveryId"
          placeholder="请输入送货单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['purchase:receive:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['purchase:receive:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['purchase:receive:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['purchase:receive:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="receiveList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="收料通知单ID" align="center" prop="id" />
      <el-table-column label="收料通知单号" align="center" prop="receiveId" />
      <el-table-column label="采购订单号" align="center" prop="poId" />
      <el-table-column label="送货单号" align="center" prop="deliveryId" />
      <el-table-column label="收料日期" align="center" prop="receiveDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.receiveDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收料人" align="center" prop="receiver" />
      <el-table-column label="总箱数" align="center" prop="totalBoxes" />
      <el-table-column label="总数量" align="center" prop="totalQuantity" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建人" align="center" prop="createdPerson" />
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['purchase:materialReceive:query']"
          >查看箱码</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['purchase:materialReceive:edit']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['purchase:receive:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['purchase:receive:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- 扫码区域 -->
        <el-card header="扫码区域" style="margin-bottom: 20px;">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="扫码" prop="scanCode">
                <el-input
                  v-model="scanCode"
                  placeholder="请输入送货单号或箱码"
                  clearable
                  @keyup.enter.native="handleScan"
                >
                  <el-button slot="append" icon="el-icon-search" @click="handleScan">扫码</el-button>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="收料人" prop="receiver">
                <el-input v-model="form.receiver" placeholder="请输入收料人" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-checkbox v-model="sameBatch" style="margin-left: 120px;">带入同批次</el-checkbox>
              <span style="margin-left: 10px; color: #666; font-size: 12px;">
                (勾选后，扫描单个箱码会自动带入同送货单的所有箱码)
              </span>
            </el-col>
          </el-row>
        </el-card>

        <!-- 收料清单区域 -->
        <el-card header="收料清单" style="margin-bottom: 20px;">
          <el-table :data="receiveItems" border>
            <el-table-column prop="poId" label="采购订单号" />
            <el-table-column prop="itemId" label="存货编码" />
            <el-table-column prop="itemName" label="存货名称" />
            <el-table-column prop="poNum" label="订单数量" />
            <el-table-column prop="payoffNum" label="未送料数量" />
            <el-table-column prop="currentDeliveryQuantity" label="本次送货数量" />
            <el-table-column prop="currentReceiveQuantity" label="本次收货数量" />
            <el-table-column prop="boxCount" label="箱数" />
          </el-table>
        </el-card>

        <!-- 箱码列表区域 -->
        <el-card header="箱码列表">
          <el-table :data="selectedBoxCodes" border>
            <el-table-column type="index" width="50" label="序号" />
            <el-table-column prop="boxId" label="箱码" />
            <el-table-column prop="boxNum" label="装箱数量" />
            <el-table-column prop="itemId" label="存货编码" />
            <el-table-column prop="itemName" label="存货名称" />
            <el-table-column prop="spec" label="规格型号" />
            <el-table-column prop="batch" label="批次" />
            <el-table-column prop="uom" label="计量单位" />
            <el-table-column prop="inspectionStatus" label="质检状态">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.inspectionStatus === 0" type="warning">未质检</el-tag>
                <el-tag v-else type="success">已质检</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="warehousingStatus" label="入库状态">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.warehousingStatus === 0" type="warning">未入库</el-tag>
                <el-tag v-else type="success">已入库</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 备注 -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看箱码对话框 -->
    <el-dialog title="箱码列表" :visible.sync="viewOpen" width="1200px" append-to-body>
      <el-table :data="currentReceive.boxCodes" border v-if="currentReceive">
        <el-table-column prop="boxId" label="箱码" />
        <el-table-column prop="boxNum" label="装箱数量" />
        <el-table-column prop="itemId" label="存货编码" />
        <el-table-column prop="itemName" label="存货名称" />
        <el-table-column prop="spec" label="规格型号" />
        <el-table-column prop="batch" label="批次" />
        <el-table-column prop="uom" label="计量单位" />
        <el-table-column prop="inspectionStatus" label="质检状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.inspectionStatus === 0" type="warning">未质检</el-tag>
            <el-tag v-else type="success">已质检</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="warehousingStatus" label="入库状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.warehousingStatus === 0" type="warning">未入库</el-tag>
            <el-tag v-else type="success">已入库</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isRejected" label="是否拒收">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.recevingStatus === 1" type="danger">是</el-tag>
            <el-tag v-else type="success">否</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>


















  </div>
</template>

<script>
import { listReceive, getReceive, delReceive, addReceive, updateReceive, scanCode } from "@/api/purchase/receive"

export default {
  name: "Receive",
  data() {
    return {
      // 收料通知单表格数据
      materialReceiveList: [],
      // 扫码输入
      scanCode: '',
      // 是否带入同批次
      sameBatch: false,

      viewOpen: false,
      // 当前查看的收料通知单
      currentReceive: null,
      // 收料清单数据
      receiveItems: [],
      // 选中的箱码
      selectedBoxCodes: [],


      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedMaterialReceiveDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 收料通知单表格数据
      receiveList: [],
      // ${subTable.functionName}表格数据
      materialReceiveDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        receiveId: null,
        poId: null,
        deliveryId: null,
        receiveDate: null,
        receiver: null,
        totalBoxes: null,
        totalQuantity: null,
        createdPerson: null,
        createdAt: null,
        updatedAt: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        receiveId: [
          { required: true, message: "收料通知单号不能为空", trigger: "blur" }
        ],
        poId: [
          { required: true, message: "采购订单号不能为空", trigger: "blur" }
        ],
        deliveryId: [
          { required: true, message: "送货单号不能为空", trigger: "blur" }
        ],
        receiveDate: [
          { required: true, message: "收料日期不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 扫码操作
    handleScan() {
      if (!this.scanCode) {
        this.$modal.msgError("请输入送货单号或箱码");
        return;
      }
      this.loading = true;
      scanCode(this.scanCode, this.sameBatch).then(response => {
        const scanData = response.data;
        // 更新表单数据
        this.form=scanData;
        this.form.deliveryId = scanData.deliveryId;
        this.form.receiveDate = scanData.receiveDate;
        this.form.receiver = scanData.receiver;

        // 更新收料清单和箱码列表
        this.receiveItems = scanData.receiveItems || [];
        this.selectedBoxCodes = scanData.boxCodes || [];

        this.loading = false;
        this.$modal.msgSuccess("扫码成功");
      }).catch(error => {
        console.error('扫码失败:', error);
        this.loading = false;
        this.$modal.msgError("扫码失败: " + (error.message || '未知错误'));
      });
    },
    // 查看箱码按钮操作
    handleView(row) {
      this.loading = true;
      getReceive(row.id).then(response => {
        this.currentReceive = response.data;
        this.viewOpen = true;
        this.loading = false;
      }).catch(error => {
        console.error('获取收料通知单详情失败:', error);
        this.loading = false;
      });
    },








    /** 查询收料通知单列表 */
    getList() {
      this.loading = true
      listReceive(this.queryParams).then(response => {
        this.receiveList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        receiveId: null,
        poId: null,
        deliveryId: null,
        receiveDate: null,
        receiver: null,
        totalBoxes: null,
        totalQuantity: null,
        remark: null,
        createdPerson: null,
        createdAt: null,
        updatedAt: null
      }
      this.materialReceiveDetailList = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加收料通知单"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getReceive(id).then(response => {
        this.selectedBoxCodes = response.data.boxCodes || [];
        this.receiveItems = response.data.receiveItems || [];
        this.open = true;
        this.title = "修改收料通知单"
      }).catch(error => {
        console.error('获取收料通知单详情失败:', error);
        this.$modal.msgError("获取详情失败");
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.selectedBoxCodes.length === 0) {
            this.$modal.msgError("请先扫码获取箱码数据");
            return;
          }

          this.loading = true;
          const materialReceiveVO = {
            ...this.form,
            receiveItems: this.receiveItems,
            boxCodes: this.selectedBoxCodes,
            totalBoxes: this.selectedBoxCodes.length,
            totalQuantity: this.selectedBoxCodes.reduce((total, box) => total + (box.boxNum || 0), 0)
          };

          if (this.form.id != null) {
            updateReceive(materialReceiveVO).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addReceive(materialReceiveVO).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除收料通知单编号为"' + ids + '"的数据项？').then(function() {
        return delReceive(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
	/** ${subTable.functionName}序号 */
    rowMaterialReceiveDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** ${subTable.functionName}添加按钮操作 */
    handleAddMaterialReceiveDetail() {
      let obj = {}
      obj.boxId = ""
      obj.recevingStatus = ""
      obj.createdAt = ""
      obj.updatedAt = ""
      this.materialReceiveDetailList.push(obj)
    },
    /** ${subTable.functionName}删除按钮操作 */
    handleDeleteMaterialReceiveDetail() {
      if (this.checkedMaterialReceiveDetail.length == 0) {
        this.$modal.msgError("请先选择要删除的${subTable.functionName}数据")
      } else {
        const materialReceiveDetailList = this.materialReceiveDetailList
        const checkedMaterialReceiveDetail = this.checkedMaterialReceiveDetail
        this.materialReceiveDetailList = materialReceiveDetailList.filter(function(item) {
          return checkedMaterialReceiveDetail.indexOf(item.index) == -1
        })
      }
    },
    /** 复选框选中数据 */
    handleMaterialReceiveDetailSelectionChange(selection) {
      this.checkedMaterialReceiveDetail = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('purchase/receive/export', {
        ...this.queryParams
      }, `receive_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
